package com.nlp.visualization.service.impl.file;

import com.nlp.visualization.service.IFileService;
import com.nlp.visualization.utils.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileServiceImpl implements IFileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);


//    @Override
//    public File upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//
//        List<File> fileList = new ArrayList<>();
//
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        String projectName = request.getContextPath();
//        String outStr = "";
//        // 文件保存目录路径
//        String savePath = request.getSession().getServletContext()
//                .getRealPath(commonUploadPath);
//        logger.info("目标路径:" + savePath);
//        // 检查目录
//        File uploadDir = new File(savePath);
//        if (!uploadDir.isDirectory()) {
//            // 如果不存在，创建文件夹
//            if (!uploadDir.exists()) {
//                uploadDir.mkdirs();
//            }
//        }
//        String dirName = request.getParameter("dir");
//        if (dirName == null) {
//            dirName = "segFile";
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
//        String ymd = sdf.format(new Date());
//        savePath += "/" + ymd + "/";
//        File dirFile = new File(savePath);
//        if (!dirFile.exists()) {
//            dirFile.mkdirs();
//        }
//        // 此处是直接采用Spring的上传
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile mf = entity.getValue();
//            String fileFullname = mf.getOriginalFilename();
//            fileFullname = fileFullname.replace('&', 'a');
//            fileFullname = fileFullname.replace(',', 'b');
//            fileFullname = fileFullname.replace('，', 'c');
//            // 扩展名
//            String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
//            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
//            File uploadFile = new File(savePath + newFileName);
//            fileList.add(uploadFile);
//            //这里会抛出IO异常
//            FileCopyUtils.copy(mf.getBytes(), uploadFile);
//            outStr += projectName + commonUploadPath + ymd + "/" + newFileName + ";";
//
//        }
//        return fileList.get(0);
//    }

    @Override
    public List<File> upload(HttpServletRequest request, HttpServletResponse response,String saveDir) throws IOException {

        List<File> fileList = new ArrayList<>();
        String commonUploadPath = PropertyUtil.getInstance("config").getProperty("upload.commmon.path")+saveDir;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String projectName = request.getContextPath();
        String outStr = "";
        // 文件保存目录路径
        String savePath = request.getSession().getServletContext()
                .getRealPath(commonUploadPath);
        logger.info("上传成功,目标路径:" + savePath);
        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            // 如果不存在，创建文件夹
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
        }
        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "segFile";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        savePath += "/" + ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 此处是直接采用Spring的上传
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileFullname = mf.getOriginalFilename();
            fileFullname = fileFullname.replace('&', 'a');
            fileFullname = fileFullname.replace(',', 'b');
            fileFullname = fileFullname.replace('，', 'c');
            // 扩展名
            String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + fileFullname.substring(0,fileFullname.lastIndexOf(".")) + "_" + new Random().nextInt(1000) + "." + fileExt;
            File uploadFile = new File(savePath + newFileName);
            fileList.add(uploadFile);
            //这里会抛出IO异常
            FileCopyUtils.copy(mf.getBytes(), uploadFile);
            outStr += projectName + commonUploadPath + ymd + "/" + newFileName + ";";

        }
        return fileList;
    }
}
